/**
 * ECP Web开发实体选择控件.
 * Copyright(c) 2012-2020 YGSoft.Inc
 * @author zhengxianwei 
 * @date 2016-05-13
 */
define(["jquery","ecp.service","jstree","ecp.utils","ecp.utils.tree","ecp.component.dialog","qzz.querygrid","ecp.utils.i18n","ecp.locate","qzz.icombobox"],
	function($,ecp,jstree,utils,treeUtils,$window,querygrid,i18n,locate){
	/**
	 * 默认参数.
	 */
	var defaultOption = {
		multiple:false,
		winOption: {
			title:i18n.select.entitiTitle,
			url : "/grm/ecp/webcore/components/select/popentity.html", 
			fade : false,  //取消动画效果
			multilayer : true,  //允许多次嵌套模态窗
            width : "760px",   //模态窗宽度 支持如 100% 600px
            maxHeight : "560px"  //模态窗body最大高度，超过时body内将出现滚动条
		}
	};
	var optionData = [
				{id:"contain", text: i18n.select.contain},
				{id:"equal", text: i18n.select.equal},
				{id:"noequal", text: i18n.select.noequal},
				{id:"greater", text: i18n.select.moreThan},
				{id:"less", text: i18n.select.lessThan}
	        ];
	var selNumHtml = '<div class="pull-left record">'+ i18n.select.selected +
		'<span class="selected-num" style="cursor: pointer;line-height: 20px;display: inline-block;height: 20px;'+
		'padding: 0 8px;border-radius: 10px;text-align: center;margin: 10px 5px;color: #fff;background: #5bc0de;">0</span>'+i18n.select.bar+
		'<ul class="seleted-list list-unstyled" style="overflow:auto; max-height:445px; display:none;">'+
		'</ul></div>';
	/**
	 * 保存选中的记录数
	 */
	var selectNodeDatas = {};
	
	/**
	 * 缓存初始化值.
	 */
	var select2Data = [];
	
	/**
	 * 声明PopSelect对象.
	 * @param {Object} option 控件的属性对象
	 */
	var PopSelect = function(option){
		//初始化
		this._init(option);
		//渲染控件
		this._render();
	}
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	PopSelect.prototype = {
			/**
			 * 初始化.
	    	 * @param {Object} option 控件的属性对象
			 */
			_init: function(option){
				this.option = option || {};
				this.serialNo = new Date().getTime();
				if(this.option.showTree){
					if(!this.option.winOption){
						this.option.winOption = {};
					}
					this.option.winOption.width = "965px";
				}
			},
			
			/**
	    	 * 渲染控件.
	    	 */
			_render: function(){
				var me = this,
					opt = $.extend(true,{},defaultOption.winOption,me.option.winOption,{
	                callback:function(container){
	                	//国际化
	                	utils.loadLocale(i18n.select,container);
	    				utils.domAttrI18n(i18n.select, container, "title");
	    				utils.domAttrI18n(i18n.select, container, "placeholder");
	                	//根据是否显示树控件设置窗口的宽度
	    			    if(me.option.showTree){
	    			    	$(".leftTD", container).css("display","");
	    			    	$(".leftTD", container).next().css("display","");
	    			    }else{
	    			    	$(".rightTD", container).css({"width":"750px","padding":"0px 2px 4px 2px"});
	    			    }
	    			    //设置树和表格高度自适应，如果winOption配置的maxHeigh小于或大于默认的都要处理
	    			    var winopt = me.option.winOption;
	    			    if(winopt && winopt.maxHeight){
	    			    	var dafualMaxHeight = parseFloat(defaultOption.winOption.maxHeight,10);
		    			    var maxHeight = parseFloat(winopt.maxHeight,10);
		    			    if(dafualMaxHeight < maxHeight || dafualMaxHeight > maxHeight){
		    			    	var tree = $("#tree_entity", container);
		    			    	var gridDiv = $(".qzz-wrapper", container);
		    			    	var slide = $(".slide-left", container);
		    			    	tree.css("height",(parseFloat(tree.css("height"),10) * maxHeight/dafualMaxHeight)-10 + "px");
		    			    	gridDiv.css("height",(parseFloat(gridDiv.css("height"),10) * maxHeight/dafualMaxHeight)-10 + "px");
		    			    	slide.css("height",(parseFloat(slide.css("height"),10) * maxHeight/dafualMaxHeight) + "px");
		    			    }
	    			    }
	    			    
	                	me._renderEntity();
	                	//显示实体窗回调
	                	if($.isFunction(me.option.showCallBack)){
	                		me.option.showCallBack.call(me,container,me.option);
	                	}
	                },
	                dialogHide:function(){
	                	select2Data = [];
				    	me.isDelete = false;
				    	selectNodeDatas = {};
	                },
	                showCloseButton:false,
	                offClick :true,  //取消点击非模态窗位置关闭窗口
	                otherButtons:[i18n.select.cancel,i18n.select.sure],  //增加两个按钮
	                otherButtonStyles:['btn-default','btn-primary'], //按钮样式,
	                clickButton:function(sender, modal, index){
	                	if(index == 1){  //确定按钮
	                		me._sureBtn();
	                	}
	                	if(index == 0){  //取消按钮
	                		modal.modal("hide");
	                	}
	                }
				});
				me.winContainer = $window.window(opt);
				$($(".modal-footer", me.winContainer).children().get(0)).before(selNumHtml);
				me._popWinEvent();
				me.isFilter = false;
		    	me.entityGrid = null;
	    	},
	    	/**
	    	 * 显示窗口.
	    	 */
	    	show: function(){
	    		var me = this;
	    		this.winContainer.modal("show");
	    		this._renderEntity();
	    		$("[buttonindex]",this.winContainer).off("click").on("click",function(event){
	    			//确认
	    			if($(event.target).attr("buttonindex") == 1){
	    				me._sureBtn();
	    			}
	    			me.hide();
	    		})
	    		me._popWinEvent();
	    	},
	    	
	    	/**
	    	 * 隐藏窗口.
	    	 */
	    	hide: function(){
	    		this.winContainer.modal("hide");
	    	},
	    	
	    	/**
	    	 * 获取选中记录明细页面html。
	    	 */
	    	getSelectDetilHtml: function(){
	    	    var popOverTemplate = '<div class="modal fade" id="selectDetail'+this.serialNo+'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="z-index:99999">'
	    	    		+ '<div class="modal-dialog modal_header_bgblue" style="width: 760px;">'
	    	    		+ '<div class="modal-content">'
	    	    		+ '<div class="modal-header">'
	    	    		+ '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'
	    	    		+ '<h4 class="modal-title" id="">'+ i18n.select.selectTitle +'</h4>'
	    	    		+ '</div>'
	    	    		+ '<div class="modal-body" style="padding: 10px 15px 15px 15px;">'
	    	    		+ '<table class="table-responsive" width="100%">'
	    	            + ' <tr>'
	    	            + '  <td style="vertical-align: top;">'
	    	            + '    <div class="treeTable">'
	    	            + '      <div class="table-responsive">'
	    	            + '        <div class="btn-group tableTopBtnGroup" role="group" aria-label="...">'
	    	            + '          <button type="button" id="delBtn" style=" border: 1px solid #ccc;border-radius: 4px;" class="btn btn-default">'+i18n.select.del+'</button>'
	    	            + '        </div>'
	    	            + '      </div>'
	    	            + '    </div>'
	    	            + '  </td>'
	    	            + '</tr>'
	    	            + '<tr>'
	    	            + '  <td style="height:300px;width:736px;"><table id="select_detail_table"></table></td>'
	    	            + '</tr>'
	    	            + '</table>'
	    	            + '</div>'
	    	            + '<div class="modal-footer">'
	    	            + '<button type="button" class="btn btn-default" data-dismiss="modal">'+i18n.select.cancel+'</button>'
	    	            + '</div>'
	    	            + '</div>'
	    	            + '</div>'
	    	            + '</div>';
	    	    return popOverTemplate;
	    	},

	    	/**
	    	 * 加载数据.
	    	 */
	    	_renderEntity: function(){
	    		this._renderTree();
	    		this._renderTable();
	    		this._renderFilter();
    			this._loadEntityData();
	    	},
	    	
	    	/**
	    	 * 初始化过滤条件.
	    	 */
	    	_renderFilter:function(){
	    		//id名称转换的项目
	    		var me = this,
					gridParam = me.option.entityGrid,
					colNames,colModels,optStr = "";
	    		if(gridParam){
	    			colNames = gridParam.colNames;
					colModels = gridParam.colModels;
	    		}
				if(!me.isFilter && colNames && colNames.length !== 0){
					var datas = [], defField = me.option.defFilterField, defType;
					//获取过滤默认选择列
					for(var i=0,j=colNames.length; i<j; i++){
					    datas.push({"id":colModels[i].name, "text":colNames[i],"dataType":colModels[i].dataType || "string"});
					    if(colModels[i].name === defField) {
					    	defType = colModels[i].dataType || "string";
					    }
					}
					var $filterNm = $("#filterName",me.winContainer).qzzcombobox({"height":34,"width":180,"data":datas,"readOnly":true,"rowHeight":30});
					//初始化过滤列选择.
					var dfv = null, dft = colModels[0].dataType || "string";
					if(defField != null) {
						dfv = defField;	
						dft = defType;
						$filterNm.setValue(dfv);
					}					
					this._initOperator(dft);
					//过滤条件变动事件.
				    $filterNm.bind("onSelect", function(index, item) {
					
		    			  var dataType = item.dataType;
		    			  me._initOperator(dataType);
		    		});
					me.isFilter = true;
				}
	    	 },
	    	 
	    	 /**
	    	  * 初始化过滤条件
	    	  */
	    	_initOperator:function(dataType){
	    		var container = this.winContainer,
	    			operator = $("#operator", container).qzzcombobox({"width":100,"height":34, "readOnly":true}),
	    			data;
				if("string"===dataType){
					data = optionData.slice(0,2);
					this._createOption(operator, data);
					operator.setValue('contain');
				}else if("number"===dataType){
					data = optionData.slice(1);
					this._createOption(operator, data);
					operator.setValue('equal');
				} else {
					data = optionData.slice(1,3);
					this._createOption(operator, data);
					operator.setValue('equal');
				}
	    	},
	    	/**
	    	 * 创建option.
	    	 */
	    	_createOption : function(optObj,data){
	    		optObj.setItemList(data);
	    	},
	    	
	    	/**
	    	 * 渲染树控件.
	    	 */
	    	_renderTree: function(){
	    		var me = this,
	    			opt = me.option,
	    			treeOpt = opt.entityTree,
	    			plugins = ["types", "search","create_node"],
	    			treeObj = $("#tree_entity", this.winContainer),
	    			treeOption;
	    		if(!opt.showTree){return;}
	    		treeOption = {
 						"treeCodeField":treeOpt.treeCodeField,
 						"treeTextField":treeOpt.treeTextField,
 						"treeType":treeOpt.treeType,
 						"treeValueField":treeOpt.treeValueField,
 						"treeFieldName":treeOpt.buildTreeField,
 						"treeCodePolicy":treeOpt.treeCodePolicy
 				};
	    		var initTreeFn = function(resultData){
	    			var treeData = treeUtils.getJsTreeJson(resultData,treeOpt);
	 				var plug = opt.entityTree && opt.entityTree.plugins;
	 				treeObj.data("treeOption",treeOption);
	 				treeObj.jstree("destroy");
	 				me.bindTreeEvent();
	 				plugins = $.extend(true, plugins, plug);
	 				treeObj.jstree({
	 					"core" : {
	 				      "themes" : {
	 				        "responsive": false,
					        "icons":false
	 				      },
	 				      'data': treeData
	 				    },
	 				    "types" : {
	 				      "default" : {
	 				        "icon" : "fa fa-folder icon-warning icon-lg"
	 				      },
	 				      "file" : {
	 				        "icon" : "fa fa-file icon-warning icon-lg"
	 				      }
	 				    },
	 				    "plugins": plugins
	 				});
	    		 }
	    		var entityTreeData = this.option.entityTreeData;
	    		if($.isFunction(entityTreeData)){
	    			entityTreeData.call(this, this.option, initTreeFn);
	    		}
	    	},
	    	
	    	/**
	    	 * 渲染表格.
	    	 */
	    	_renderTable:function(){
	    		var me = this,
	    			opt = me.option;
	    		if(!me.entityGrid){
	    			var initParam = {
	    					"Align":"alClient",
	    					"treeGrid": false,
	    					"shrinkToFit": true
	    				}
    				initParam.multiselect = opt.multiple;
    				initParam = $.extend(true, initParam, this.option.entityGrid);
					//F1235014 解决qzzGrid在4列以下出现横向滚动条情况
					var colNms = initParam.colNames;
					if(colNms && colNms.length < 4){
						initParam.suitToFit = true;
					}
    				me.entityGrid = $('#entity_table', this.winContainer).qzzquerygrid(initParam);
    				me.bindGridEvent();
	    		}
	    	},
	    	
	    	
	    	/**
	    	 * 加载实体对象数据.
	    	 */
	    	_loadEntityData:function(filter){
	    		var me = this,
	    			opt = me.option,
					container = me.winContainer,
					initGrid = function(resultData){
	    				if(!resultData){
	    					resultData = [];
	    				}
						me.entityGrid.value(resultData);
					};
				if(!filter){
					filter = me.getFieldFilter();
				}
				var entityGridData = opt.entityGridData;
				if($.isFunction(entityGridData)){
					filter.selectTreeNodeId = me.selectTreeNodeData;
					entityGridData.call(this, initGrid, opt, filter);
				}
	    	},
	    	/**
	    	 * 设置选择行数。
	    	 */
	    	_setSelectedNum: function (node,selectState){
				var me = this,
					count = 0,
					opt = me.option,
					idField = opt.idField,
					selectRowData = me.entityGrid.getSelectedRowData();
				if(selectRowData){
					if(opt.multiple){
						if(selectRowData.length !== 0){
							$.each(selectRowData,function(){
								selectNodeDatas[this[idField]]=this;
							})
						}else if(node && node.selectAll === true){
							selectNodeDatas = {};
						}
					}else{
						selectNodeDatas = {};
						selectNodeDatas[selectRowData[idField]]=selectRowData;
					}
				}
				if(node && selectState === false){
					delete selectNodeDatas[node.data[idField]];
				}
				for(var i in selectNodeDatas){
					count ++;
				}
				$(".selected-num", me.winContainer).text(count);
				
			},
			
			/**
			 * 树查找无结果时给提示.
			 */
			checkTreeSearch: function(val){
				var me = this,
					container = me.winContainer,
					treeObj = $("#tree_entity", container);
				treeObj.jstree(true).search(val);
				if(treeObj.find("a.jstree-search").length === 0 && utils.notEmpty(val)){
					utils.notify({
						message:i18n.select.noMatchRecords,
				        delay:1000//延迟3秒关闭
					}); 
				}
			},
			
			/**
			 * 绑定的树事件.
			 */
			bindTreeEvent: function(){
				var me = this,
	    			opt = me.option,
	    			treeOpt = opt.entityTree,
					container = me.winContainer,
					treeObj = $("#tree_entity", container);
				//显示/隐藏左边树
	    		$("td > i", container).off("click").on("click",function(){
	    			      
	    		    var $me = $(this),
	    		    	leftTD = $(".leftTD", container),
	    		    	rightTD = $(".rightTD", container),
	    		    	treeTitle = $(".treeTitle", container),
	    		    	etreeExp = $("#btn_entityTreeExpand", container);
	    		    if($me.hasClass("slide-left")) {
	    				$("td.leftTD > .select2", container).fadeOut(50);
	    				$("td.leftTD > .treeTop", container).fadeOut(50);
	    				$("td.leftTD > .treeContainer", container).fadeOut(50);
	    		    	$me.removeClass("slide-left").addClass("slide-right");
	    		    	$me.attr("title",i18n.select.showTree);
	    		    	leftTD.animate({"width":"0"},200);
	    		    	rightTD.animate({"width":"918px"},200).css("padding-bottom","4px");
	    				container.find(".modal-body").css("padding-left","0px");
	    		    	me.entityGrid.setWidth(931);
	    		    } else if($me.hasClass("slide-right")){
	    		    	$me.removeClass("slide-right").addClass("slide-left");
	    		    	$me.attr("title",i18n.select.hideTree);
	    		    	leftTD.animate({"width":"300px"},200,
								function(){
								$("td.leftTD > .select2", container).fadeIn(50);
								$("td.leftTD > .treeTop", container).fadeIn(50);
								$("td.leftTD > .treeContainer", container).fadeIn(50);
							}
						);
						container.find(".modal-body").css("padding-left","15px");
						rightTD.animate({"width":"618px"},200);
	    		    	//设置表格宽度
	    		    	me.entityGrid.setWidth(617);
	    		    }
	    		});
	    		
		    	//展开缩起节点.
		    	$("#btn_entityTreeExpand", container).off("click").on("click", function(){
		 			var treeObj = $("#tree_entity", container);
		 			var first = treeObj.jstree('get_container_ul').children(":first").attr("id");
		 			if (treeObj.jstree("is_open",first)) {
						 treeObj.jstree("close_all");
						 $(this).find("i").removeClass("iconfont icon-quanbushouqi").addClass("fa fa-arrows");
		 			} else {
						 treeObj.jstree("open_all");
						 $(this).find("i").removeClass("fa fa-arrows").addClass("iconfont icon-quanbushouqi")
		 			}
		 		});
		    	
		 		//搜索
				var isEnterFlag = false;
				// 搜索框keyup事件
				$("#entity_search", container).off("keyup").on("keyup", function(e) {
					var $me = this;
					isEnterFlag = false;
					if (e.keyCode == "13") {
						isEnterFlag = true;
						me.checkTreeSearch($me.value.trim());
//						treeObj.jstree(true).search(me.value.trim());
					}else{
						if(this.timeout){
							  window.clearTimeout(this.timeout)
						}
						this.timeout = window.setTimeout(function(){
							if(isEnterFlag === false){
								me.checkTreeSearch($me.value.trim());
//								treeObj.jstree(true).search(me.value.trim());
							}
						},1000)
					}
				});

				locate.render({
					container: $('#entity_search',container), //必须
					jstreeObject: $('#tree_entity',container),//必须
					callback: function(val){ //可选 触发搜索后的回调
					},
					width: '300px',//可选 默认300px
					placeholder: '输入关键字 , 自动定位'//可选 无特殊情况不需配置该选项
				});

	    		//树的展开事件（处理懒加载）.
				treeObj.bind("open_node.jstree",function(event,data){
					
					var treeLazyDatas = opt.treeLazyDatas;
					if(opt.isLazy !== true || !$.isFunction(treeLazyDatas)){return;}
					var node = data.node;
					//顶层节点展开不做处理.
					if(node.parent=="#"){
						//分类做为树时特殊处理
						var ids = node.children;
						for(var i=0, len=ids.length; i<len; i++){
							var _node = data.instance.get_node(ids[i]);
							if(!_node.original.leaf){
								_node.children.push(ids[i]);
								_node.children_d.push(ids[i]);
								_node.state.opened=false;
								$("#"+ids[i], container).attr("class","jstree-node  jstree-closed");
							}
						}
						return;
					}
					var callback = function(result){
							if(!result || result.length === 0){return;}
							var res = treeUtils.getJsTreeJson(result,treeOpt);
							treeObj._append_json_data(node, res , function(){});
					}
					var filter = {
							id : node.id,
							parent: node.parent,
							text: node.text,
							original: node.original
					}
					treeLazyDatas.call(this, opt, callback, filter);
					
	    		});
	    		  
	    		//选择树节点事件
				treeObj.bind("select_node.jstree",function(event,data){
	    			 var option = {
	    					 entity: me,
	    					 entityTreeObj : treeObj,
	    					 entityGridObj : me.entityGrid,
	    					 data: data,
	    					 event: event,
	    					 treeOption: $(this).data("treeOption")
	    			 }
	    			 var tsnFn = opt.treeSelectNodeFn;
	    			 if($.isFunction(tsnFn)){
	    				 tsnFn.call(this,option);
	    			 }
	    		});
			},
			/**
			 * 根据过滤条件查询表格
			 */
			queryGrid: function(){
				var me = this;
				//获得查询条件
	    		var fieldFilter = me.getFieldFilter();
	    		me._loadEntityData(fieldFilter);
			},
	    	/**
	    	 * 绑定的表格事件.
	    	 */
	    	bindGridEvent: function(){
	    		var me = this;
	    		//选择复选框事件.
				me.entityGrid.bind("onCheckChanged",function(cNode, selectState){
					me._setSelectedNum(cNode, selectState);
				});
				//选中行事件.
				me.entityGrid.bind("onSelectEcpRow",function(){
					if(!me.option.multiple){
						me._setSelectedNum();
					}
				});
				//全选复选框点击事件.
				me.entityGrid.bind("onSelectAll",function(checked, fieldName){
					me._setSelectedNum({selectAll:true});
				})
				//数据加载完成后事件.
				me.entityGrid.bind("gridComplete",function(){
					//初始化选中行
					me._initSelectRow();
				})
				var container = me.winContainer;
				//查询按钮事件
				$("#entityqueryBtn",container).off("click").on("click",function(){
					var treeObj = $("#tree_entity", container);
					if(me.option.showTree){
						me.selectTreeNodeData = treeObj.jstree(true).get_selected();
					}
					me.queryGrid();
				})
                
                //绑定双击行事件（单选），直接关闭窗口
                if(!me.option.multiple){
                    me.entityGrid.bind("onDBClick",function(){
					    me._sureBtn();
				    })
                }

				//输入自动查询
				var isEnterFlag = false;
				// 搜索框keyup事件
				$("#entityFilterText", container).off("keyup").on("keyup", function(e) {
					var that = this;
					isEnterFlag = false;
					if (e.keyCode == "13") {
						isEnterFlag = true;
						me.queryGrid();
					}else{
						if(this.timeout){
							  window.clearTimeout(this.timeout)
						}
						this.timeout = window.setTimeout(function(){
							if(isEnterFlag === false){
								me.queryGrid();
							}
						},1000)
					}
				});
				
	    	},
	    	
	    	/**
			 * 确定按钮
			 */
			_sureBtn: function(){
				var me = this,
	    			opt = me.option,
	    			popSelected = [],
	    			container = me.winContainer;
				if(!$.isEmptyObject(selectNodeDatas)){
	 				for(var i in selectNodeDatas){
	 					popSelected.push(selectNodeDatas[i]);
	 				}
	 				//多选，循环处理
	 				if(!opt.multiple){
		 				popSelected = popSelected[0];
		 				popSelected.id = popSelected[opt.idField];
		 				popSelected.text = popSelected[opt.textField];
		 			}
	 			}else{
	 				if(!opt.multiple){
	 					popSelected = {};
	 				}
	 			}
	 			container.modal("hide");
	 			opt.closeCallBack && opt.closeCallBack(popSelected);
			},
			
	    	/**
	    	 * 窗口内控件绑定事件.
	    	 */
	    	_popWinEvent: function(){
	    		var me = this,
	    			option = me.option,
	    			container = me.winContainer;
		 		//查询过滤。
		 		$("#entityqueryBtn", container).off("click").on("click",function(){
		 			me._queryFilter();
		 		});
		 		//单选时隐藏选中树
		 		if(!option.multiple){
		 			$(".record", container).hide();
		 		}
		 		var to = false;
		 		$("#entityFilterText", container).keyup(function(){
		 			if(to){clearTimeout(to)};
		 			to = setTimeout(function(){
		 				me._queryFilter();
		 			},1000);
		 		});
		 		
		 		$(".selected-num", container).off("click").on("click",function(){
		 			//单选不弹窗
		 			if(!option.multiple){
		 				return;
		 			}
		 			if($(this).text() == "0"){return;}
//		 			var selectRowData = me.entityGrid.getSelectedRowData();
		 			if(!$.isEmptyObject(selectNodeDatas)){
		 				//弹出选中记录明细页面
				 		var pophtml = $("#selectDetail"+me.serialNo);
					    if (!pophtml.length) {
					    	$("body").append(me.getSelectDetilHtml());
					    	pophtml = $("#selectDetail"+me.serialNo);
					    }
					    me.winSelContainer = pophtml;
					    pophtml.modal("show");
					    pophtml.off("hidden.bs.modal").on("hidden.bs.modal", function(){
//					    		pophtml.remove();
					    });
					    if(!me.option.showTree){
					    	$(".modal_header_bgblue", pophtml).css("width","660px");
					    	$("#select_detail_table", pophtml).parent().css({width:"630px",height:"270px"});
					    }
					    var selectRowData = [];
						if(option.pager){
							for(var i in selectNodeDatas){
					    		selectRowData.push(selectNodeDatas[i]);
							}
						}else{
							selectRowData = me.entityGrid.getSelectedRowData();
						}
					    me._renderSelDetailGrid(selectRowData);
		 			}
		 		})
	    	},
	    	
	    	/**
	    	 * 渲染选中明细表格.
	    	 */
	    	_renderSelDetailGrid: function(selectRowData){
	    		var me = this,
    				opt = me.option;
	    		if(!me.selDetailGrid){
	    			var initParam = {
	    					"height": 200,
	    					"treeGrid": false,
	    					"shrinkToFit": true,
	    					"multiselect": true,
							"Align":"alClient"
	    				}
	    			//没有树控件时调整表格高度
	    			if(!me.option.showTree){
	    				initParam.height = 270;
	    			}
	    			initParam = $.extend(true, initParam, opt.entityGrid);
					me.selDetailGrid = $('#select_detail_table', this.winSelContainer).qzzquerygrid(initParam);
	    		}
	    		me.selDetailGrid.value(selectRowData);
	    		$("#delBtn", me.winSelContainer).off("click").on("click",function(){
	    			var data = me.selDetailGrid.getSelectedRowData();
	    			//无记录时不处理
	    			if(data == null){return;}
	    			if(data.length === 0){
	    				utils.notify(i18n.select.selectOneRecord);
	    				return;
	    			}else{
	    				var count = 0,
	    					delId = [],
	    					idField = opt.idField, id;
	    				//删除选中记录列表数据
						//var selectDatas = me.selDetailGrid.getSelectedRowData() || [];
						//$.each(selectDatas,function(){
						//	id = this[idField];
						//	delId.push(id);
						//	count ++;
						//	delete selectNodeDatas[id]
						//});
						//me.selDetailGrid.delRecord(delId);
	    				me.selDetailGrid.each(function(node){
							if(this.isSelected(node)){
								id = node.data[idField];
								delId.push(id);
								this.delRecord();
								count ++;
								delete selectNodeDatas[id]
							}
						}, function() {
							me.selDetailGrid.first();
							//重新设置选中数
							var $selNum = $(".selected-num", me.winContainer);
							$selNum.text($selNum.text()*1 - count);
							//取消选中主表记录
							me.entityGrid.dataSet.each(function(node){
								if($.inArray(node.data[idField],delId) > -1){
									this.setUnSelect(node);
								}
							}, function() {
								me.entityGrid.first();
								//单选删除标识
								if(!opt.multiple){
									me.isDelete = true;
									select2Data = [];
								}
								me.entityGrid.setTitleChecked("@MUL", false);
							});							
						});						
	    			}
	    		})
	    	},
	    	/**
	    	 * 获得表格控件对象.
	    	 */
	    	getEntityGrid: function(){
	    		return this.entityGrid;
	    	},
	    	
	    	/**
	    	 * 查询过滤.
	    	 */
	    	_queryFilter:function(){
	    		//在查询前保存选中的值 
	    		var me = this,
	    			opt = me.option,
	    			idField = opt.idField,
	    			selData = me.entityGrid.getSelectedRowData();
	    		if(selData){
	    			if(opt.multiple){
	    				$.each(selData,function(){
			    			selectNodeDatas[this[idField]] = this;
			    		})
	    			}else{
	    				selectNodeDatas[selData[idField]] = selData;
	    			}
	    		}
	    		me.queryGrid();
	    	},
	    	/**
	    	 * 获得过滤条件对象
	    	 */
	    	getFieldFilter: function(){
	    		//获得查询条件
	    		var fieldFilter={},
	    			container = this.winContainer;
	    		fieldFilter.fieldName =  $("#filterName", container).qzzcombobox(true).getValue();
	    		fieldFilter.fieldOperator =  $("#operator", container).qzzcombobox(true).getValue();
	    		fieldFilter.fieldValue = $("#entityFilterText", container).val();
	    		if(fieldFilter.fieldValue == ""){
	    			fieldFilter.fieldName="";
	    		}
	    		return fieldFilter;
	    	},
	    	/**
	    	 * 设置树的选中值
	    	 * @param {Array} data 数据
	    	 */
	    	setSelectValue: function(data){
	    		this.selectValue = data;
	    	},
	    	/**
			 * 初始化选中行.
			 */
			_initSelectRow: function(){
				var me = this,
					opt = me.option,
					selectRowData = me.selectValue;//me.control.select2("data");
				//显示初始化时被选中个数 wugang
				$(".selected-num", me.winContainer).text(selectRowData && selectRowData.length || 0);
				if(select2Data.length === 0 && me.isDelete !== true){
					if($.isPlainObject(selectRowData) && selectRowData != null){
						select2Data.push(selectRowData);
					}
					if($.isArray(selectRowData) && selectRowData.length !== 0){
						select2Data = selectRowData;
					}
				}
				me.entityGrid.first();
				if(select2Data.length !== 0 || !$.isEmptyObject(selectNodeDatas)){
					var idField = opt.idField;
					var textField = opt.textField;
					if(opt.multiple){
						var ids = [];
						if(select2Data.length !== 0){
							$.each(select2Data,function(){
								selectNodeDatas[this.id] = this;
							})
						}
						$.each(selectNodeDatas,function(i){
							ids.push(i);
						})
						
						me.entityGrid.dataSet.each(function(node){
							var id = this.getValue(idField)+"";
							if($.inArray(id,ids)>-1){
								this.setSelect();
							}
						})
						me._setSelectedNum();
					}else{
						var text;
						if(select2Data.length === 0){
							for(var i in selectNodeDatas){
								text = selectNodeDatas[i][textField];
							}
						}else{
							selectNodeDatas = {};
							text = select2Data[0].text;
							selectNodeDatas[select2Data[0][idField]] = select2Data[0];
							me._setSelectedNum();
						}
						me.entityGrid.setFocus();
						me.entityGrid.locate(textField,text);
					}
				}else{
					$(".selected-num", me.winContainer).text(0);
				}
			},
	    	
	    	/**
	    	 * 设置option.
	    	 * @param {Object} option 控件属性
	    	 */
	    	setOption:function(option){
	    		if(!option || !$.isPlainObject(option) || $.isEmptyObject(option)){
	    			return;
	    		}
	    		this.option = $.extend(true,this.option,option);
	    	},
	    	
	    	/**
	    	 * 获取option
	    	 * @return {Object} option 控件属性对象
	    	 */
	    	getOption:function(){
	    		return this.option;
	    	},
	    	
	    	/**
	    	 *值变动事件.
	    	 */
	    	change:function(data){
	    		//todo
	    	}
	};
	return PopSelect;
});